/**
 * @author:linjiye
 * @date:2025/1/5
 * @desc:
 **/

import {StyleSheet, Text, TouchableOpacity, View, Image} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcTextInput from "@/components/FcTextInput";
import KeywordHighlighter from "@/components/KeywordHighlighter";
import NoData from "@/components/NoData";
import FcButton from "@/components/FcButton";
import {router} from "expo-router";
import FcModal from "@/components/FcModal";
import FormTitle from "@/components/FormTitle";
import {Flex, Toast} from "@ant-design/react-native";
import {
    useDeleteGroupMutation,
    useEditGroupMutation,
    useGetParentListQuery
} from "@/store/api/aiOriginality/aiOriginalityApi";
import FcSearch from "@/components/FcSearch";

type Props = {}

const editGroup = (props: Props) => {
    const [searchText, setSearchText] = useState('')
    const [list, setList] = useState([])
    const [currentItem, setCurrentItem] = useState({})
    const [selectData, setSelectData] = useState([])
    const [isDelete, setIsDelete] = useState(false)
    const [isEdit, setIsEdit] = useState(false)
    const [typeList, setTypeList] = useState([
        {
            name: '提供产品',
            id: 1,
        },{
            name: '提供服务',
            id: 2,
        },{
            name: '经营场景',
            id: 3,
        }
    ])
    const [typeId, setTypeId] = useState('')

    const {data:groupResData,isSuccess:groupSuccess, refetch:groupRefetch}= useGetParentListQuery?.({
        types: typeId,
        name: searchText
    })
    const [deleteGroupFun] = useDeleteGroupMutation()
    const [editGroupFun] = useEditGroupMutation()

    useEffect(() => {
        if (groupResData) {
            let list = groupResData?.result || []
            const gArr = []
            list.forEach((item) => {
                gArr.push({
                    title: item.groupName,
                    isSelected: false,
                    ...item
                })
            })
            setList(gArr)
        }
    },[groupSuccess,groupResData])

    const handleSelectItem = (item, index) => {
        let newList = [],newSelectData = []
        newList = [...list]
        newList[index].isSelected = !newList[index].isSelected
        newSelectData = newList?.filter(item => item.isSelected)
        setList(newList)
        setSelectData(newSelectData)
    }

    const handleComplete = () => {
        router.back()
    }

    const handleDelete = () => {
        setIsDelete(true)
    }

    const handleType = (val) => {
        setTypeId(val.id)
    }

    const handleEdit = (val) => {
        setCurrentItem(val)
        setIsEdit(true)
    }

    function takeDelete() {
        deleteGroupFun({
            ids: selectData?.map(item => item.id)
        }).then(res => {
            if (res?.data?.code === 200) {
                Toast.info('删除成功')
                setIsDelete(false)
                setSelectData([])
                // groupRefetch()
            }
        })
    }

    function takeEdit() {
        editGroupFun({
            id: currentItem.id,
            name: currentItem.name,
            parentId: 0,
        }).then(res => {
            if (res?.data?.code === 200) {
                Toast.info('编辑成功')
                setIsEdit(false)
                setCurrentItem({})
                // groupRefetch()
            }
        })
    }

    return (
        <PageScrollView
            isTransparentTab
            pageTab={
                <PageTabBar
                    style={{marginVertical: 10}}
                    title={'分组列表'}
                    right={
                        <FcButton
                            onClick={() => handleComplete()}
                            type='BjJB'
                            colors={['#6989FF', '#C65EFD']}
                            style={{width: 48, height: 28, justifyContent: 'center'}}
                            itemStyle={{borderRadius: 8, fontSize: 12}}
                            textName='完成'/>

                    }
                />
            }
            pageHeader={
                <FcSearch searchText={searchText} onSearch={(val) => setSearchText(val)}/>
            }
            pageBottom={
                <View style={styles.page_bottom}>
                    <Text style={styles.delete_num}>已选 {selectData?.length} 个</Text>
                    <TouchableOpacity style={styles.delete_btn} onPress={() =>selectData?.length>0 && handleDelete()}>
                        <Text style={{
                            fontFamily: 'FcIconFont',
                            fontSize: 20,
                            color: selectData?.length>0 ? 'rgba(250,81,81,1)' : 'rgba(250,81,81,.3)'
                        }}>&#xe61d;</Text>
                        <Text
                            style={[styles.delete_text, selectData?.length>0 && styles.delete_active]}>删除</Text>
                    </TouchableOpacity>
                </View>
            }
        >
            <View>
                <View style={styles.search_item_wrap}>
                    <KeywordHighlighter
                        text="全部分组"
                        keywords=""
                        textStyle={styles.search_text}
                        textHeightLightStyle={{color: '#2856FF'}}
                    />
                </View>
                {list?.map((item, index) => (
                    <View style={styles.item_wrap} key={index}>
                        <View style={styles.item_left}>
                            <TouchableOpacity style={[styles.select_icon, item.isSelected && styles.select_active]}
                                              onPress={() => handleSelectItem(item, index)}>
                                {item.isSelected && <Text
                                    style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                            </TouchableOpacity>
                            <KeywordHighlighter
                                text={item.name}
                                keywords={searchText}
                                textStyle={styles.search_text}
                                textHeightLightStyle={{color: '#2856FF'}}
                            />
                            <Text style={{color: 'rgba(0,0,0,0.5)'}}>({item.count})</Text>
                        </View>
                        <View style={styles.item_right}>
                            <TouchableOpacity onPress={() => handleEdit(item)}>
                                <Text style={{
                                    fontFamily: 'FcIconFont',
                                    fontSize: 20,
                                    color: 'rgba(0,0,0,0.5)'
                                }}>&#xe630;</Text>
                            </TouchableOpacity>
                            <TouchableOpacity>
                                <Text style={{
                                    fontFamily: 'FcIconFont',
                                    fontSize: 20,
                                    color: 'rgba(0,0,0,0.5)',
                                    marginLeft: 20
                                }}>&#xe633;</Text>
                            </TouchableOpacity>
                        </View>
                    </View>

                ))}
                {list?.length <= 0 &&
                    <View style={{
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        paddingTop: 60,
                        paddingBottom: 120
                    }}>
                        <NoData hintText='暂无分组'/>
                        {/*<FcButton*/}
                        {/*    onClick={() => setIsAdd(true)}*/}
                        {/*    type='BjJB'*/}
                        {/*    colors={['#6989FF', '#C65EFD']}*/}
                        {/*    style={{width: 74, height: 32, justifyContent: 'center'}}*/}
                        {/*    itemStyle={{borderRadius: 8}}*/}
                        {/*    textName='去新增'></FcButton>*/}
                    </View>
                }
            </View>
            <FcModal
                isOpen={isDelete}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsDelete(false)}
                style={styles.modal_default}
                titleText={'确认要删除吗？'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsDelete(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => takeDelete(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前分组将被删除哦~</Text>
            </FcModal>
            <FcModal
                isOpen={isEdit}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsEdit(false)}
                style={styles.modal_default}
                titleText={'编辑分组'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsEdit(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => takeEdit(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <View style={{paddingBottom: 20}}>
                    <FormTitle style={{paddingTop: 0}} isLeftIcon title='选择类目' />
                    <Flex wrap='wrap' style={styles.type_menu}>
                        <FcButton
                            type='txtBK'
                            style={[styles.type_menu_item]}
                            itemStyle={{width: '100%', height: '100%'}}
                            textName={currentItem.type == 1 ? '提供产品' : (currentItem.type == 2 ? '提供服务' : '经营场景')} borderWidth={1}></FcButton>
                    </Flex>
                    <FcTextInput text={currentItem.name} placeholder={'请输入分组名称'}
                                 onChangeText={(val) => setCurrentItem({...currentItem,name:val})}
                                 height={56}/>
                </View>
            </FcModal>
        </PageScrollView>
    )
}


export default editGroup

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
        borderRadius: 8,
        paddingHorizontal: 16,
    },
    tabBar_btn: {
        width: 64,
        height: 28,
        display: 'flex',
        justifyContent: "center",
        alignItems: "center",
        fontSize: 12,
        color: '#2856FF',
        borderRadius: 8,
        backgroundColor: 'white'
    },
    search_item_wrap: {
        flexDirection: 'row',
        minHeight: 56,
        display: 'flex',
        alignItems: "center",
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(0,0,0,0.1)',
        borderBottomWidth: 0.5,
    },
    search_text: {
        color: 'rgba(0, 0, 0, 0.9)',
        fontSize: 17,
    },
    item_wrap: {
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "space-between",
        minHeight: 56,
        display: 'flex',
        borderBottomColor: 'rgba(0,0,0,0.1)',
        borderBottomWidth: 0.5,
    },
    item_left: {
        flexDirection: 'row',
        alignItems: "center"
    },
    select_icon: {
        width: 20,
        height: 20,
        borderRadius: '50%',
        borderWidth: 1,
        borderColor: 'rgba(0,0,0,0.5)',
        marginRight: 12,
    },
    select_active: {
        borderColor: '#2856FF',
        backgroundColor: '#2856FF',
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "center"
    },
    item_right: {
        flexDirection: 'row',
        alignItems: "center"
    },
    page_bottom: {
        backgroundColor: 'white',
        width: '100%',
        height: 48,
        position: "relative",
    },
    delete_num: {
        lineHeight: 48,
        fontSize: 12,
        color: 'rgba(0,0,0,0.3)',
        paddingHorizontal: 16,
    },
    delete_btn: {
        position: "absolute",
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "row",
    },
    delete_text: {
        fontSize: 14,
        color: 'rgba(250,81,81,0.3)'
    },
    delete_active: {
        color: 'rgba(250,81,81,1)'
    },
    modal_default: {
        width: 280,
        borderBottomRightRadius: 12,
        borderBottomLeftRadius: 12,
    },

    type_menu: {
        display: "flex",
        flexWrap: "wrap",
        flexDirection: "row",
        marginLeft: -3,
        marginBottom: 16
    },
    type_menu_item: {
        width: 78,
        height: 40,
        lineHeight: 40,
        borderRadius: 8,
        marginHorizontal: 3,
        marginBottom: 6
    },
})